<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Writing custom model fields &mdash; Django 1.7.8.dev20150401230226 documentation</title>
    
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.7.8.dev20150401230226',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="Django 1.7.8.dev20150401230226 documentation" href="../index.html" />
    <link rel="up" title="“How-to” guides" href="index.html" />
    <link rel="next" title="Custom Lookups" href="custom-lookups.html" />
    <link rel="prev" title="Writing custom django-admin commands" href="custom-management-commands.html" />



 
<script type="text/javascript" src="../templatebuiltins.js"></script>
<script type="text/javascript">
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);
</script>


  </head>
  <body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="custom-management-commands.html" title="Writing custom django-admin commands">previous</a>
     |
    <a href="index.html" title="&amp;#8220;How-to&amp;#8221; guides" accesskey="U">up</a>
   |
    <a href="custom-lookups.html" title="Custom Lookups">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-custom-model-fields">
            
  <div class="section" id="s-writing-custom-model-fields">
<span id="writing-custom-model-fields"></span><h1>Writing custom model fields<a class="headerlink" href="#writing-custom-model-fields" title="Permalink to this headline">¶</a></h1>
<div class="section" id="s-introduction">
<span id="introduction"></span><h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../topics/db/models.html"><em>model reference</em></a> documentation explains how to use
Django&#8217;s standard field classes &#8211; <a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a>,
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField" title="django.db.models.DateField"><tt class="xref py py-class docutils literal"><span class="pre">DateField</span></tt></a>, etc. For many purposes, those classes are
all you&#8217;ll need. Sometimes, though, the Django version won&#8217;t meet your precise
requirements, or you&#8217;ll want to use a field that is entirely different from
those shipped with Django.</p>
<p>Django&#8217;s built-in field types don&#8217;t cover every possible database column type &#8211;
only the common types, such as <tt class="docutils literal"><span class="pre">VARCHAR</span></tt> and <tt class="docutils literal"><span class="pre">INTEGER</span></tt>. For more obscure
column types, such as geographic polygons or even user-created types such as
<a class="reference external" href="http://www.postgresql.org/docs/current/interactive/sql-createtype.html">PostgreSQL custom types</a>, you can define your own Django <tt class="docutils literal"><span class="pre">Field</span></tt> subclasses.</p>
<p>Alternatively, you may have a complex Python object that can somehow be
serialized to fit into a standard database column type. This is another case
where a <tt class="docutils literal"><span class="pre">Field</span></tt> subclass will help you use your object with your models.</p>
<div class="section" id="s-our-example-object">
<span id="our-example-object"></span><h3>Our example object<a class="headerlink" href="#our-example-object" title="Permalink to this headline">¶</a></h3>
<p>Creating custom fields requires a bit of attention to detail. To make things
easier to follow, we&#8217;ll use a consistent example throughout this document:
wrapping a Python object representing the deal of cards in a hand of <a class="reference external" href="http://en.wikipedia.org/wiki/Contract_bridge">Bridge</a>.
Don&#8217;t worry, you don&#8217;t have to know how to play Bridge to follow this example.
You only need to know that 52 cards are dealt out equally to four players, who
are traditionally called <em>north</em>, <em>east</em>, <em>south</em> and <em>west</em>.  Our class looks
something like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Hand</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;A hand of cards (bridge style)&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">north</span><span class="p">,</span> <span class="n">east</span><span class="p">,</span> <span class="n">south</span><span class="p">,</span> <span class="n">west</span><span class="p">):</span>
        <span class="c"># Input parameters are lists of cards (&#39;Ah&#39;, &#39;9s&#39;, etc)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">north</span> <span class="o">=</span> <span class="n">north</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">east</span> <span class="o">=</span> <span class="n">east</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">south</span> <span class="o">=</span> <span class="n">south</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">west</span> <span class="o">=</span> <span class="n">west</span>

    <span class="c"># ... (other possibly useful methods omitted) ...</span>
</pre></div>
</div>
<p>This is just an ordinary Python class, with nothing Django-specific about it.
We&#8217;d like to be able to do things like this in our models (we assume the
<tt class="docutils literal"><span class="pre">hand</span></tt> attribute on the model is an instance of <tt class="docutils literal"><span class="pre">Hand</span></tt>):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">example</span> <span class="o">=</span> <span class="n">MyModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">example</span><span class="o">.</span><span class="n">hand</span><span class="o">.</span><span class="n">north</span><span class="p">)</span>

<span class="n">new_hand</span> <span class="o">=</span> <span class="n">Hand</span><span class="p">(</span><span class="n">north</span><span class="p">,</span> <span class="n">east</span><span class="p">,</span> <span class="n">south</span><span class="p">,</span> <span class="n">west</span><span class="p">)</span>
<span class="n">example</span><span class="o">.</span><span class="n">hand</span> <span class="o">=</span> <span class="n">new_hand</span>
<span class="n">example</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>We assign to and retrieve from the <tt class="docutils literal"><span class="pre">hand</span></tt> attribute in our model just like
any other Python class. The trick is to tell Django how to handle saving and
loading such an object.</p>
<p>In order to use the <tt class="docutils literal"><span class="pre">Hand</span></tt> class in our models, we <strong>do not</strong> have to change
this class at all. This is ideal, because it means you can easily write
model support for existing classes where you cannot change the source code.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You might only be wanting to take advantage of custom database column
types and deal with the data as standard Python types in your models;
strings, or floats, for example. This case is similar to our <tt class="docutils literal"><span class="pre">Hand</span></tt>
example and we&#8217;ll note any differences as we go along.</p>
</div>
</div>
</div>
<div class="section" id="s-background-theory">
<span id="background-theory"></span><h2>Background theory<a class="headerlink" href="#background-theory" title="Permalink to this headline">¶</a></h2>
<div class="section" id="s-database-storage">
<span id="database-storage"></span><h3>Database storage<a class="headerlink" href="#database-storage" title="Permalink to this headline">¶</a></h3>
<p>The simplest way to think of a model field is that it provides a way to take a
normal Python object &#8211; string, boolean, <tt class="docutils literal"><span class="pre">datetime</span></tt>, or something more
complex like <tt class="docutils literal"><span class="pre">Hand</span></tt> &#8211; and convert it to and from a format that is useful
when dealing with the database (and serialization, but, as we&#8217;ll see later,
that falls out fairly naturally once you have the database side under control).</p>
<p>Fields in a model must somehow be converted to fit into an existing database
column type. Different databases provide different sets of valid column types,
but the rule is still the same: those are the only types you have to work
with. Anything you want to store in the database must fit into one of
those types.</p>
<p>Normally, you&#8217;re either writing a Django field to match a particular database
column type, or there&#8217;s a fairly straightforward way to convert your data to,
say, a string.</p>
<p>For our <tt class="docutils literal"><span class="pre">Hand</span></tt> example, we could convert the card data to a string of 104
characters by concatenating all the cards together in a pre-determined order &#8211;
say, all the <em>north</em> cards first, then the <em>east</em>, <em>south</em> and <em>west</em> cards. So
<tt class="docutils literal"><span class="pre">Hand</span></tt> objects can be saved to text or character columns in the database.</p>
</div>
<div class="section" id="s-what-does-a-field-class-do">
<span id="what-does-a-field-class-do"></span><h3>What does a field class do?<a class="headerlink" href="#what-does-a-field-class-do" title="Permalink to this headline">¶</a></h3>
<p>All of Django&#8217;s fields (and when we say <em>fields</em> in this document, we always
mean model fields and not <a class="reference internal" href="../ref/forms/fields.html"><em>form fields</em></a>) are subclasses
of <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.Field</span></tt></a>. Most of the information that Django records
about a field is common to all fields &#8211; name, help text, uniqueness and so
forth. Storing all that information is handled by <tt class="docutils literal"><span class="pre">Field</span></tt>. We&#8217;ll get into the
precise details of what <tt class="docutils literal"><span class="pre">Field</span></tt> can do later on; for now, suffice it to say
that everything descends from <tt class="docutils literal"><span class="pre">Field</span></tt> and then customizes key pieces of the
class behavior.</p>
<p>It&#8217;s important to realize that a Django field class is not what is stored in
your model attributes. The model attributes contain normal Python objects. The
field classes you define in a model are actually stored in the <tt class="docutils literal"><span class="pre">Meta</span></tt> class
when the model class is created (the precise details of how this is done are
unimportant here). This is because the field classes aren&#8217;t necessary when
you&#8217;re just creating and modifying attributes. Instead, they provide the
machinery for converting between the attribute value and what is stored in the
database or sent to the <a class="reference internal" href="../topics/serialization.html"><em>serializer</em></a>.</p>
<p>Keep this in mind when creating your own custom fields. The Django <tt class="docutils literal"><span class="pre">Field</span></tt>
subclass you write provides the machinery for converting between your Python
instances and the database/serializer values in various ways (there are
differences between storing a value and using a value for lookups, for
example). If this sounds a bit tricky, don&#8217;t worry &#8211; it will become clearer in
the examples below. Just remember that you will often end up creating two
classes when you want a custom field:</p>
<ul class="simple">
<li>The first class is the Python object that your users will manipulate.
They will assign it to the model attribute, they will read from it for
displaying purposes, things like that. This is the <tt class="docutils literal"><span class="pre">Hand</span></tt> class in our
example.</li>
<li>The second class is the <tt class="docutils literal"><span class="pre">Field</span></tt> subclass. This is the class that knows
how to convert your first class back and forth between its permanent
storage form and the Python form.</li>
</ul>
</div>
</div>
<div class="section" id="s-writing-a-field-subclass">
<span id="writing-a-field-subclass"></span><h2>Writing a field subclass<a class="headerlink" href="#writing-a-field-subclass" title="Permalink to this headline">¶</a></h2>
<p>When planning your <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass, first give some
thought to which existing <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> class your new field
is most similar to. Can you subclass an existing Django field and save yourself
some work? If not, you should subclass the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a>
class, from which everything is descended.</p>
<p>Initializing your new field is a matter of separating out any arguments that are
specific to your case from the common arguments and passing the latter to the
<tt class="docutils literal"><span class="pre">__init__()</span></tt> method of <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> (or your parent
class).</p>
<p>In our example, we&#8217;ll call our field <tt class="docutils literal"><span class="pre">HandField</span></tt>. (It&#8217;s a good idea to call
your <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass <tt class="docutils literal"><span class="pre">&lt;Something&gt;Field</span></tt>, so it&#8217;s
easily identifiable as a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass.) It doesn&#8217;t
behave like any existing field, so we&#8217;ll subclass directly from
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>

    <span class="n">description</span> <span class="o">=</span> <span class="s">&quot;A hand of cards (bridge style)&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;max_length&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">104</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">HandField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>Our <tt class="docutils literal"><span class="pre">HandField</span></tt> accepts most of the standard field options (see the list
below), but we ensure it has a fixed length, since it only needs to hold 52
card values plus their suits; 104 characters in total.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Many of Django&#8217;s model fields accept options that they don&#8217;t do anything
with. For example, you can pass both
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><tt class="xref py py-attr docutils literal"><span class="pre">editable</span></tt></a> and
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><tt class="xref py py-attr docutils literal"><span class="pre">auto_now</span></tt></a> to a
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField" title="django.db.models.DateField"><tt class="xref py py-class docutils literal"><span class="pre">django.db.models.DateField</span></tt></a> and it will simply ignore the
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><tt class="xref py py-attr docutils literal"><span class="pre">editable</span></tt></a> parameter
(<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><tt class="xref py py-attr docutils literal"><span class="pre">auto_now</span></tt></a> being set implies
<tt class="docutils literal"><span class="pre">editable=False</span></tt>). No error is raised in this case.</p>
<p class="last">This behavior simplifies the field classes, because they don&#8217;t need to
check for options that aren&#8217;t necessary. They just pass all the options to
the parent class and then don&#8217;t use them later on. It&#8217;s up to you whether
you want your fields to be more strict about the options they select, or to
use the simpler, more permissive behavior of the current fields.</p>
</div>
<p>The <tt class="docutils literal"><span class="pre">Field.__init__()</span></tt> method takes the following parameters:</p>
<ul class="simple">
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.verbose_name" title="django.db.models.Field.verbose_name"><tt class="xref py py-attr docutils literal"><span class="pre">verbose_name</span></tt></a></li>
<li><tt class="docutils literal"><span class="pre">name</span></tt></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.primary_key" title="django.db.models.Field.primary_key"><tt class="xref py py-attr docutils literal"><span class="pre">primary_key</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField.max_length" title="django.db.models.CharField.max_length"><tt class="xref py py-attr docutils literal"><span class="pre">max_length</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique" title="django.db.models.Field.unique"><tt class="xref py py-attr docutils literal"><span class="pre">unique</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.blank" title="django.db.models.Field.blank"><tt class="xref py py-attr docutils literal"><span class="pre">blank</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.null" title="django.db.models.Field.null"><tt class="xref py py-attr docutils literal"><span class="pre">null</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_index" title="django.db.models.Field.db_index"><tt class="xref py py-attr docutils literal"><span class="pre">db_index</span></tt></a></li>
<li><tt class="docutils literal"><span class="pre">rel</span></tt>: Used for related fields (like <a class="reference internal" href="../ref/models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><tt class="xref py py-class docutils literal"><span class="pre">ForeignKey</span></tt></a>). For advanced
use only.</li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.default" title="django.db.models.Field.default"><tt class="xref py py-attr docutils literal"><span class="pre">default</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.editable" title="django.db.models.Field.editable"><tt class="xref py py-attr docutils literal"><span class="pre">editable</span></tt></a></li>
<li><tt class="docutils literal"><span class="pre">serialize</span></tt>: If <tt class="docutils literal"><span class="pre">False</span></tt>, the field will not be serialized when the model
is passed to Django&#8217;s <a class="reference internal" href="../topics/serialization.html"><em>serializers</em></a>. Defaults to
<tt class="docutils literal"><span class="pre">True</span></tt>.</li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_date" title="django.db.models.Field.unique_for_date"><tt class="xref py py-attr docutils literal"><span class="pre">unique_for_date</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_month" title="django.db.models.Field.unique_for_month"><tt class="xref py py-attr docutils literal"><span class="pre">unique_for_month</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.unique_for_year" title="django.db.models.Field.unique_for_year"><tt class="xref py py-attr docutils literal"><span class="pre">unique_for_year</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.choices" title="django.db.models.Field.choices"><tt class="xref py py-attr docutils literal"><span class="pre">choices</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.help_text" title="django.db.models.Field.help_text"><tt class="xref py py-attr docutils literal"><span class="pre">help_text</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_column" title="django.db.models.Field.db_column"><tt class="xref py py-attr docutils literal"><span class="pre">db_column</span></tt></a></li>
<li><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_tablespace" title="django.db.models.Field.db_tablespace"><tt class="xref py py-attr docutils literal"><span class="pre">db_tablespace</span></tt></a>: Only for index creation, if the
backend supports <a class="reference internal" href="../topics/db/tablespaces.html"><em>tablespaces</em></a>. You can usually
ignore this option.</li>
<li><tt class="docutils literal"><span class="pre">auto_created</span></tt>: <tt class="docutils literal"><span class="pre">True</span></tt> if the field was automatically created, as for the
<a class="reference internal" href="../ref/models/fields.html#django.db.models.OneToOneField" title="django.db.models.OneToOneField"><tt class="xref py py-class docutils literal"><span class="pre">OneToOneField</span></tt></a> used by model inheritance. For
advanced use only.</li>
</ul>
<p>All of the options without an explanation in the above list have the same
meaning they do for normal Django fields. See the <a class="reference internal" href="../ref/models/fields.html"><em>field documentation</em></a> for examples and details.</p>
<div class="section" id="s-field-deconstruction">
<span id="s-custom-field-deconstruct-method"></span><span id="field-deconstruction"></span><span id="custom-field-deconstruct-method"></span><h3>Field deconstruction<a class="headerlink" href="#field-deconstruction" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 1.7:</span> <p><tt class="docutils literal"><span class="pre">deconstruct()</span></tt> is part of the migrations framework in Django 1.7 and
above. If you have custom fields from previous versions they will
need this method added before you can use them with migrations.</p>
</div>
<p>The counterpoint to writing your <tt class="docutils literal"><span class="pre">__init__()</span></tt> method is writing the
<tt class="docutils literal"><span class="pre">deconstruct()</span></tt> method. This method tells Django how to take an instance
of your new field and reduce it to a serialized form - in particular, what
arguments to pass to <tt class="docutils literal"><span class="pre">__init__()</span></tt> to re-create it.</p>
<p>If you haven&#8217;t added any extra options on top of the field you inherited from,
then there&#8217;s no need to write a new <tt class="docutils literal"><span class="pre">deconstruct()</span></tt> method. If, however,
you&#8217;re, changing the arguments passed in <tt class="docutils literal"><span class="pre">__init__()</span></tt> (like we are in
<tt class="docutils literal"><span class="pre">HandField</span></tt>), you&#8217;ll need to supplement the values being passed.</p>
<p>The contract of <tt class="docutils literal"><span class="pre">deconstruct()</span></tt> is simple; it returns a tuple of four items:
the field&#8217;s attribute name, the full import path of the field class, the
positional arguments (as a list), and the keyword arguments (as a dict). Note
this is different from the <tt class="docutils literal"><span class="pre">deconstruct()</span></tt> method <a class="reference internal" href="../topics/migrations.html#custom-deconstruct-method"><em>for custom classes</em></a> which returns a tuple of three things.</p>
<p>As a custom field author, you don&#8217;t need to care about the first two values;
the base <tt class="docutils literal"><span class="pre">Field</span></tt> class has all the code to work out the field&#8217;s attribute
name and import path. You do, however, have to care about the positional
and keyword arguments, as these are likely the things you are changing.</p>
<p>For example, in our <tt class="docutils literal"><span class="pre">HandField</span></tt> class we&#8217;re always forcibly setting
max_length in <tt class="docutils literal"><span class="pre">__init__()</span></tt>. The <tt class="docutils literal"><span class="pre">deconstruct()</span></tt> method on the base <tt class="docutils literal"><span class="pre">Field</span></tt>
class will see this and try to return it in the keyword arguments; thus,
we can drop it from the keyword arguments for readability:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;max_length&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">104</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">HandField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">deconstruct</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">HandField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">deconstruct</span><span class="p">()</span>
        <span class="k">del</span> <span class="n">kwargs</span><span class="p">[</span><span class="s">&quot;max_length&quot;</span><span class="p">]</span>
        <span class="k">return</span> <span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span>
</pre></div>
</div>
<p>If you add a new keyword argument, you need to write code to put its value
into <tt class="docutils literal"><span class="pre">kwargs</span></tt> yourself:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">CommaSepField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="s">&quot;Implements comma-separated storage of lists&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">separator</span><span class="o">=</span><span class="s">&quot;,&quot;</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">separator</span> <span class="o">=</span> <span class="n">separator</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">CommaSepField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">deconstruct</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">CommaSepField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">deconstruct</span><span class="p">()</span>
        <span class="c"># Only include kwarg if it&#39;s not the default</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">separator</span> <span class="o">!=</span> <span class="s">&quot;,&quot;</span><span class="p">:</span>
            <span class="n">kwargs</span><span class="p">[</span><span class="s">&#39;separator&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">separator</span>
        <span class="k">return</span> <span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span>
</pre></div>
</div>
<p>More complex examples are beyond the scope of this document, but remember -
for any configuration of your Field instance, <tt class="docutils literal"><span class="pre">deconstruct()</span></tt> must return
arguments that you can pass to <tt class="docutils literal"><span class="pre">__init__</span></tt> to reconstruct that state.</p>
<p>Pay extra attention if you set new default values for arguments in the
<tt class="docutils literal"><span class="pre">Field</span></tt> superclass; you want to make sure they&#8217;re always included, rather
than disappearing if they take on the old default value.</p>
<p>In addition, try to avoid returning values as positional arguments; where
possible, return values as keyword arguments for maximum future compatibility.
Of course, if you change the names of things more often than their position
in the constructor&#8217;s argument list, you might prefer positional, but bear in
mind that people will be reconstructing your field from the serialized version
for quite a while (possibly years), depending how long your migrations live for.</p>
<p>You can see the results of deconstruction by looking in migrations that include
the field, and you can test deconstruction in unit tests by just deconstructing
and reconstructing the field:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">name</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="n">my_field_instance</span><span class="o">.</span><span class="n">deconstruct</span><span class="p">()</span>
<span class="n">new_instance</span> <span class="o">=</span> <span class="n">MyField</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">my_field_instance</span><span class="o">.</span><span class="n">some_attribute</span><span class="p">,</span> <span class="n">new_instance</span><span class="o">.</span><span class="n">some_attribute</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-the-subfieldbase-metaclass">
<span id="the-subfieldbase-metaclass"></span><h3>The <tt class="docutils literal"><span class="pre">SubfieldBase</span></tt> metaclass<a class="headerlink" href="#the-subfieldbase-metaclass" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="django.db.models.django.db.models.SubfieldBase">
<em class="property">class </em><tt class="descclassname">django.db.models.</tt><tt class="descname">SubfieldBase</tt><a class="headerlink" href="#django.db.models.django.db.models.SubfieldBase" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>As we indicated in the <a class="reference internal" href="#introduction">introduction</a>, field subclasses are often needed for
two reasons: either to take advantage of a custom database column type, or to
handle complex Python types. Obviously, a combination of the two is also
possible. If you&#8217;re only working with custom database column types and your
model fields appear in Python as standard Python types direct from the
database backend, you don&#8217;t need to worry about this section.</p>
<p>If you&#8217;re handling custom Python types, such as our <tt class="docutils literal"><span class="pre">Hand</span></tt> class, we need to
make sure that when Django initializes an instance of our model and assigns a
database value to our custom field attribute, we convert that value into the
appropriate Python object. The details of how this happens internally are a
little complex, but the code you need to write in your <tt class="docutils literal"><span class="pre">Field</span></tt> class is
simple: make sure your field subclass uses a special metaclass:</p>
<p>For example, on Python 2:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>

    <span class="n">description</span> <span class="o">=</span> <span class="s">&quot;A hand of cards (bridge style)&quot;</span>

    <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">SubfieldBase</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>On Python 3, in lieu of setting the <tt class="docutils literal"><span class="pre">__metaclass__</span></tt> attribute, add
<tt class="docutils literal"><span class="pre">metaclass</span></tt> to the class definition:</p>
<div class="highlight-python"><div class="highlight"><pre>class HandField(models.Field, metaclass=models.SubfieldBase):
    ...
</pre></div>
</div>
<p>If you want your code to work on Python 2 &amp; 3, you can use
<a class="reference external" href="http://pythonhosted.org/six/index.html#six.with_metaclass" title="(in six v1.9)"><tt class="xref py py-func docutils literal"><span class="pre">six.with_metaclass()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.utils.six</span> <span class="kn">import</span> <span class="n">with_metaclass</span>

<span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">with_metaclass</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">SubfieldBase</span><span class="p">,</span> <span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">)):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>This ensures that the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> method will always be called when the
attribute is initialized.</p>
<div class="section" id="s-modelforms-and-custom-fields">
<span id="modelforms-and-custom-fields"></span><h4><tt class="docutils literal"><span class="pre">ModelForm</span></tt>s and custom fields<a class="headerlink" href="#modelforms-and-custom-fields" title="Permalink to this headline">¶</a></h4>
<p>If you use <a class="reference internal" href="#django.db.models.django.db.models.SubfieldBase" title="django.db.models.django.db.models.SubfieldBase"><tt class="xref py py-class docutils literal"><span class="pre">SubfieldBase</span></tt></a>, <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> will be
called every time an instance of the field is assigned a value (in addition to
its usual call when retrieving the value from the database). This means that
whenever a value may be assigned to the field, you need to ensure that it will
be of the correct datatype, or that you handle any exceptions.</p>
<p>This is especially important if you use <a class="reference internal" href="../topics/forms/modelforms.html"><em>ModelForms</em></a>. When saving a ModelForm, Django will use
form values to instantiate model instances. However, if the cleaned
form data can&#8217;t be used as valid input to the field, the normal form
validation process will break.</p>
<p>Therefore, you must ensure that the form field used to represent your
custom field performs whatever input validation and data cleaning is
necessary to convert user-provided form input into a
<tt class="docutils literal"><span class="pre">to_python()</span></tt>-compatible model field value. This may require writing a
custom form field, and/or implementing the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.formfield" title="django.db.models.Field.formfield"><tt class="xref py py-meth docutils literal"><span class="pre">formfield()</span></tt></a> method on
your field to return a form field class whose <tt class="docutils literal"><span class="pre">to_python()</span></tt> returns the
correct datatype.</p>
</div>
</div>
<div class="section" id="s-documenting-your-custom-field">
<span id="documenting-your-custom-field"></span><h3>Documenting your custom field<a class="headerlink" href="#documenting-your-custom-field" title="Permalink to this headline">¶</a></h3>
<p>As always, you should document your field type, so users will know what it is.
In addition to providing a docstring for it, which is useful for developers,
you can also allow users of the admin app to see a short description of the
field type via the <a class="reference internal" href="../ref/contrib/admin/admindocs.html"><em>django.contrib.admindocs</em></a> application. To do this simply provide
descriptive text in a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.description" title="django.db.models.Field.description"><tt class="xref py py-attr docutils literal"><span class="pre">description</span></tt></a> class attribute of your custom
field. In the above example, the description displayed by the <tt class="docutils literal"><span class="pre">admindocs</span></tt>
application for a <tt class="docutils literal"><span class="pre">HandField</span></tt> will be &#8216;A hand of cards (bridge style)&#8217;.</p>
<p>In the <a class="reference internal" href="../ref/contrib/admin/admindocs.html#module-django.contrib.admindocs" title="django.contrib.admindocs: Django's admin documentation generator."><tt class="xref py py-mod docutils literal"><span class="pre">django.contrib.admindocs</span></tt></a> display, the field description is
interpolated with <tt class="docutils literal"><span class="pre">field.__dict__</span></tt> which allows the description to
incorporate arguments of the field. For example, the description for
<a class="reference internal" href="../ref/models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a> is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">description</span> <span class="o">=</span> <span class="n">_</span><span class="p">(</span><span class="s">&quot;String (up to </span><span class="si">%(max_length)s</span><span class="s">)&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-useful-methods">
<span id="useful-methods"></span><h3>Useful methods<a class="headerlink" href="#useful-methods" title="Permalink to this headline">¶</a></h3>
<p>Once you&#8217;ve created your <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> subclass and set up
the <tt class="docutils literal"><span class="pre">__metaclass__</span></tt>, you might consider overriding a few standard methods,
depending on your field&#8217;s behavior. The list of methods below is in
approximately decreasing order of importance, so start from the top.</p>
<div class="section" id="s-custom-database-types">
<span id="s-id1"></span><span id="custom-database-types"></span><span id="id1"></span><h4>Custom database types<a class="headerlink" href="#custom-database-types" title="Permalink to this headline">¶</a></h4>
<p>Say you&#8217;ve created a PostgreSQL custom type called <tt class="docutils literal"><span class="pre">mytype</span></tt>. You can
subclass <tt class="docutils literal"><span class="pre">Field</span></tt> and implement the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">MytypeField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&#39;mytype&#39;</span>
</pre></div>
</div>
<p>Once you have <tt class="docutils literal"><span class="pre">MytypeField</span></tt>, you can use it in any model, just like any other
<tt class="docutils literal"><span class="pre">Field</span></tt> type:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">80</span><span class="p">)</span>
    <span class="n">something_else</span> <span class="o">=</span> <span class="n">MytypeField</span><span class="p">()</span>
</pre></div>
</div>
<p>If you aim to build a database-agnostic application, you should account for
differences in database column types. For example, the date/time column type
in PostgreSQL is called <tt class="docutils literal"><span class="pre">timestamp</span></tt>, while the same column in MySQL is called
<tt class="docutils literal"><span class="pre">datetime</span></tt>. The simplest way to handle this in a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a>
method is to check the <tt class="docutils literal"><span class="pre">connection.settings_dict['ENGINE']</span></tt> attribute.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyDateField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">connection</span><span class="o">.</span><span class="n">settings_dict</span><span class="p">[</span><span class="s">&#39;ENGINE&#39;</span><span class="p">]</span> <span class="o">==</span> <span class="s">&#39;django.db.backends.mysql&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="s">&#39;datetime&#39;</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="s">&#39;timestamp&#39;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method is called by Django when the framework
constructs the <tt class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></tt> statements for your application &#8211; that is,
when you first create your tables. It is also called when constructing a
<tt class="docutils literal"><span class="pre">WHERE</span></tt> clause that includes the model field &#8211; that is, when you retrieve data
using QuerySet methods like <tt class="docutils literal"><span class="pre">get()</span></tt>, <tt class="docutils literal"><span class="pre">filter()</span></tt>, and <tt class="docutils literal"><span class="pre">exclude()</span></tt> and have
the model field as an argument. It&#8217;s not called at any other time, so it can afford to
execute slightly complex code, such as the <tt class="docutils literal"><span class="pre">connection.settings_dict</span></tt> check in
the above example.</p>
<p>Some database column types accept parameters, such as <tt class="docutils literal"><span class="pre">CHAR(25)</span></tt>, where the
parameter <tt class="docutils literal"><span class="pre">25</span></tt> represents the maximum column length. In cases like these,
it&#8217;s more flexible if the parameter is specified in the model rather than being
hard-coded in the <tt class="docutils literal"><span class="pre">db_type()</span></tt> method. For example, it wouldn&#8217;t make much
sense to have a <tt class="docutils literal"><span class="pre">CharMaxlength25Field</span></tt>, shown here:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># This is a silly example of hard-coded parameters.</span>
<span class="k">class</span> <span class="nc">CharMaxlength25Field</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&#39;char(25)&#39;</span>

<span class="c"># In the model:</span>
<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">my_field</span> <span class="o">=</span> <span class="n">CharMaxlength25Field</span><span class="p">()</span>
</pre></div>
</div>
<p>The better way of doing this would be to make the parameter specifiable at run
time &#8211; i.e., when the class is instantiated. To do that, just implement
<tt class="docutils literal"><span class="pre">Field.__init__()</span></tt>, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># This is a much more flexible example.</span>
<span class="k">class</span> <span class="nc">BetterCharField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">max_length</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">max_length</span> <span class="o">=</span> <span class="n">max_length</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">BetterCharField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">db_type</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&#39;char(</span><span class="si">%s</span><span class="s">)&#39;</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">max_length</span>

<span class="c"># In the model:</span>
<span class="k">class</span> <span class="nc">MyModel</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="c"># ...</span>
    <span class="n">my_field</span> <span class="o">=</span> <span class="n">BetterCharField</span><span class="p">(</span><span class="mi">25</span><span class="p">)</span>
</pre></div>
</div>
<p>Finally, if your column requires truly complex SQL setup, return <tt class="docutils literal"><span class="pre">None</span></tt> from
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a>. This will cause Django&#8217;s SQL creation code to skip
over this field. You are then responsible for creating the column in the right
table in some other way, of course, but this gives you a way to tell Django to
get out of the way.</p>
</div>
<div class="section" id="s-converting-database-values-to-python-objects">
<span id="s-id2"></span><span id="converting-database-values-to-python-objects"></span><span id="id2"></span><h4>Converting database values to Python objects<a class="headerlink" href="#converting-database-values-to-python-objects" title="Permalink to this headline">¶</a></h4>
<p>If your custom <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field" title="django.db.models.Field"><tt class="xref py py-class docutils literal"><span class="pre">Field</span></tt></a> class deals with data structures that are more
complex than strings, dates, integers or floats, then you&#8217;ll need to override
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a>. As a general rule, the method should deal gracefully
with any of the following arguments:</p>
<ul class="simple">
<li>An instance of the correct type (e.g., <tt class="docutils literal"><span class="pre">Hand</span></tt> in our ongoing example).</li>
<li>A string (e.g., from a deserializer).</li>
<li>Whatever the database returns for the column type you&#8217;re using.</li>
</ul>
<p>In our <tt class="docutils literal"><span class="pre">HandField</span></tt> class, we&#8217;re storing the data as a VARCHAR field in the
database, so we need to be able to process strings and <tt class="docutils literal"><span class="pre">Hand</span></tt> instances in
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">re</span>

<span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">to_python</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">Hand</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">value</span>

        <span class="c"># The string case.</span>
        <span class="n">p1</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">&#39;.{26}&#39;</span><span class="p">)</span>
        <span class="n">p2</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s">&#39;..&#39;</span><span class="p">)</span>
        <span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="n">p2</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">p1</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="n">value</span><span class="p">)]</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">4</span><span class="p">:</span>
            <span class="k">raise</span> <span class="n">ValidationError</span><span class="p">(</span><span class="s">&quot;Invalid input for a Hand instance&quot;</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">Hand</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
</pre></div>
</div>
<p>Notice that we always return a <tt class="docutils literal"><span class="pre">Hand</span></tt> instance from this method. That&#8217;s the
Python object type we want to store in the model&#8217;s attribute. If anything is
going wrong during value conversion, you should raise a
<a class="reference internal" href="../ref/exceptions.html#django.core.exceptions.ValidationError" title="django.core.exceptions.ValidationError"><tt class="xref py py-exc docutils literal"><span class="pre">ValidationError</span></tt></a> exception.</p>
<p><strong>Remember:</strong> If your custom field needs the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> method to be
called when it is created, you should be using <a class="reference internal" href="#the-subfieldbase-metaclass">The SubfieldBase metaclass</a>
mentioned earlier. Otherwise <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> won&#8217;t be called
automatically.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If your custom field allows <tt class="docutils literal"><span class="pre">null=True</span></tt>, any field method that takes
<tt class="docutils literal"><span class="pre">value</span></tt> as an argument, like <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> and
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a>, should handle the case when <tt class="docutils literal"><span class="pre">value</span></tt> is
<tt class="docutils literal"><span class="pre">None</span></tt>.</p>
</div>
</div>
<div class="section" id="s-converting-python-objects-to-query-values">
<span id="s-id3"></span><span id="converting-python-objects-to-query-values"></span><span id="id3"></span><h4>Converting Python objects to query values<a class="headerlink" href="#converting-python-objects-to-query-values" title="Permalink to this headline">¶</a></h4>
<p>Since using a database requires conversion in both ways, if you override
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.to_python" title="django.db.models.Field.to_python"><tt class="xref py py-meth docutils literal"><span class="pre">to_python()</span></tt></a> you also have to override <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a>
to convert Python objects back to query values.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">get_prep_value</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="s">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">l</span><span class="p">)</span> <span class="k">for</span> <span class="n">l</span> <span class="ow">in</span> <span class="p">(</span><span class="n">value</span><span class="o">.</span><span class="n">north</span><span class="p">,</span>
                <span class="n">value</span><span class="o">.</span><span class="n">east</span><span class="p">,</span> <span class="n">value</span><span class="o">.</span><span class="n">south</span><span class="p">,</span> <span class="n">value</span><span class="o">.</span><span class="n">west</span><span class="p">)])</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If your custom field uses the <tt class="docutils literal"><span class="pre">CHAR</span></tt>, <tt class="docutils literal"><span class="pre">VARCHAR</span></tt> or <tt class="docutils literal"><span class="pre">TEXT</span></tt>
types for MySQL, you must make sure that <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a>
always returns a string type. MySQL performs flexible and unexpected
matching when a query is performed on these types and the provided
value is an integer, which can cause queries to include unexpected
objects in their results. This problem cannot occur if you always
return a string type from <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a>.</p>
</div>
</div>
<div class="section" id="s-converting-query-values-to-database-values">
<span id="s-id4"></span><span id="converting-query-values-to-database-values"></span><span id="id4"></span><h4>Converting query values to database values<a class="headerlink" href="#converting-query-values-to-database-values" title="Permalink to this headline">¶</a></h4>
<p>Some data types (for example, dates) need to be in a specific format
before they can be used by a database backend.
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_value()</span></tt></a> is the method where those conversions should
be made. The specific connection that will be used for the query is
passed as the <tt class="docutils literal"><span class="pre">connection</span></tt> parameter. This allows you to use
backend-specific conversion logic if it is required.</p>
<p>For example, Django uses the following method for its
<a class="reference internal" href="../ref/models/fields.html#django.db.models.BinaryField" title="django.db.models.BinaryField"><tt class="xref py py-class docutils literal"><span class="pre">BinaryField</span></tt></a>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">get_db_prep_value</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="n">prepared</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span>
    <span class="n">value</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">BinaryField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">get_db_prep_value</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="n">prepared</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">value</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">connection</span><span class="o">.</span><span class="n">Database</span><span class="o">.</span><span class="n">Binary</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">value</span>
</pre></div>
</div>
<p>In case your custom field needs a special conversion when being saved that is
not the same as the conversion used for normal query parameters, you can
override <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_db_prep_save" title="django.db.models.Field.get_db_prep_save"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_save()</span></tt></a>.</p>
</div>
<div class="section" id="s-preprocessing-values-before-saving">
<span id="s-id5"></span><span id="preprocessing-values-before-saving"></span><span id="id5"></span><h4>Preprocessing values before saving<a class="headerlink" href="#preprocessing-values-before-saving" title="Permalink to this headline">¶</a></h4>
<p>If you want to preprocess the value just before saving, you can use
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.pre_save" title="django.db.models.Field.pre_save"><tt class="xref py py-meth docutils literal"><span class="pre">pre_save()</span></tt></a>. For example, Django&#8217;s
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateTimeField" title="django.db.models.DateTimeField"><tt class="xref py py-class docutils literal"><span class="pre">DateTimeField</span></tt></a> uses this method to set the attribute
correctly in the case of <a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now" title="django.db.models.DateField.auto_now"><tt class="xref py py-attr docutils literal"><span class="pre">auto_now</span></tt></a> or
<a class="reference internal" href="../ref/models/fields.html#django.db.models.DateField.auto_now_add" title="django.db.models.DateField.auto_now_add"><tt class="xref py py-attr docutils literal"><span class="pre">auto_now_add</span></tt></a>.</p>
<p>If you do override this method, you must return the value of the attribute at
the end. You should also update the model&#8217;s attribute if you make any changes
to the value so that code holding references to the model will always see the
correct value.</p>
</div>
<div class="section" id="s-preparing-values-for-use-in-database-lookups">
<span id="s-id6"></span><span id="preparing-values-for-use-in-database-lookups"></span><span id="id6"></span><h4>Preparing values for use in database lookups<a class="headerlink" href="#preparing-values-for-use-in-database-lookups" title="Permalink to this headline">¶</a></h4>
<p>As with value conversions, preparing a value for database lookups is a
two phase process.</p>
<p><a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_lookup" title="django.db.models.Field.get_prep_lookup"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_lookup()</span></tt></a> performs the first phase of lookup preparation:
type conversion and data validation.</p>
<p>Prepares the <tt class="docutils literal"><span class="pre">value</span></tt> for passing to the database when used in a lookup (a
<tt class="docutils literal"><span class="pre">WHERE</span></tt> constraint in SQL). The <tt class="docutils literal"><span class="pre">lookup_type</span></tt> parameter will be one of the
valid Django filter lookups: <tt class="docutils literal"><span class="pre">exact</span></tt>, <tt class="docutils literal"><span class="pre">iexact</span></tt>, <tt class="docutils literal"><span class="pre">contains</span></tt>, <tt class="docutils literal"><span class="pre">icontains</span></tt>,
<tt class="docutils literal"><span class="pre">gt</span></tt>, <tt class="docutils literal"><span class="pre">gte</span></tt>, <tt class="docutils literal"><span class="pre">lt</span></tt>, <tt class="docutils literal"><span class="pre">lte</span></tt>, <tt class="docutils literal"><span class="pre">in</span></tt>, <tt class="docutils literal"><span class="pre">startswith</span></tt>, <tt class="docutils literal"><span class="pre">istartswith</span></tt>,
<tt class="docutils literal"><span class="pre">endswith</span></tt>, <tt class="docutils literal"><span class="pre">iendswith</span></tt>, <tt class="docutils literal"><span class="pre">range</span></tt>, <tt class="docutils literal"><span class="pre">year</span></tt>, <tt class="docutils literal"><span class="pre">month</span></tt>, <tt class="docutils literal"><span class="pre">day</span></tt>,
<tt class="docutils literal"><span class="pre">isnull</span></tt>, <tt class="docutils literal"><span class="pre">search</span></tt>, <tt class="docutils literal"><span class="pre">regex</span></tt>, and <tt class="docutils literal"><span class="pre">iregex</span></tt>.</p>
<div class="versionadded">
<span class="title">New in Django 1.7:</span> <p>If you are using <a class="reference internal" href="custom-lookups.html"><em>Custom lookups</em></a> the
<tt class="docutils literal"><span class="pre">lookup_type</span></tt> can be any <tt class="docutils literal"><span class="pre">lookup_name</span></tt> used by the project&#8217;s custom
lookups.</p>
</div>
<p>Your method must be prepared to handle all of these <tt class="docutils literal"><span class="pre">lookup_type</span></tt> values and
should raise either a <tt class="docutils literal"><span class="pre">ValueError</span></tt> if the <tt class="docutils literal"><span class="pre">value</span></tt> is of the wrong sort (a
list when you were expecting an object, for example) or a <tt class="docutils literal"><span class="pre">TypeError</span></tt> if
your field does not support that type of lookup. For many fields, you can get
by with handling the lookup types that need special handling for your field
and pass the rest to the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_db_prep_lookup" title="django.db.models.Field.get_db_prep_lookup"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_lookup()</span></tt></a> method of the parent
class.</p>
<p>If you needed to implement <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_db_prep_save" title="django.db.models.Field.get_db_prep_save"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_save()</span></tt></a>, you will usually need to
implement <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_lookup" title="django.db.models.Field.get_prep_lookup"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_lookup()</span></tt></a>. If you don&#8217;t, <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_prep_value" title="django.db.models.Field.get_prep_value"><tt class="xref py py-meth docutils literal"><span class="pre">get_prep_value()</span></tt></a> will
be called by the default implementation, to manage <tt class="docutils literal"><span class="pre">exact</span></tt>, <tt class="docutils literal"><span class="pre">gt</span></tt>, <tt class="docutils literal"><span class="pre">gte</span></tt>,
<tt class="docutils literal"><span class="pre">lt</span></tt>, <tt class="docutils literal"><span class="pre">lte</span></tt>, <tt class="docutils literal"><span class="pre">in</span></tt> and <tt class="docutils literal"><span class="pre">range</span></tt> lookups.</p>
<p>You may also want to implement this method to limit the lookup types that could
be used with your custom field type.</p>
<p>Note that, for <tt class="docutils literal"><span class="pre">&quot;range&quot;</span></tt> and <tt class="docutils literal"><span class="pre">&quot;in&quot;</span></tt> lookups, <tt class="docutils literal"><span class="pre">get_prep_lookup</span></tt> will receive
a list of objects (presumably of the right type) and will need to convert them
to a list of things of the right type for passing to the database. Most of the
time, you can reuse <tt class="docutils literal"><span class="pre">get_prep_value()</span></tt>, or at least factor out some common
pieces.</p>
<p>For example, the following code implements <tt class="docutils literal"><span class="pre">get_prep_lookup</span></tt> to limit the
accepted lookup types to <tt class="docutils literal"><span class="pre">exact</span></tt> and <tt class="docutils literal"><span class="pre">in</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">get_prep_lookup</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">lookup_type</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="c"># We only handle &#39;exact&#39; and &#39;in&#39;. All others are errors.</span>
        <span class="k">if</span> <span class="n">lookup_type</span> <span class="o">==</span> <span class="s">&#39;exact&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_prep_value</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
        <span class="k">elif</span> <span class="n">lookup_type</span> <span class="o">==</span> <span class="s">&#39;in&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">get_prep_value</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">value</span><span class="p">]</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s">&#39;Lookup type </span><span class="si">%r</span><span class="s"> not supported.&#39;</span> <span class="o">%</span> <span class="n">lookup_type</span><span class="p">)</span>
</pre></div>
</div>
<p>For performing database-specific data conversions required by a lookup,
you can override <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_db_prep_lookup" title="django.db.models.Field.get_db_prep_lookup"><tt class="xref py py-meth docutils literal"><span class="pre">get_db_prep_lookup()</span></tt></a>.</p>
</div>
<div class="section" id="s-specifying-the-form-field-for-a-model-field">
<span id="s-specifying-form-field-for-model-field"></span><span id="specifying-the-form-field-for-a-model-field"></span><span id="specifying-form-field-for-model-field"></span><h4>Specifying the form field for a model field<a class="headerlink" href="#specifying-the-form-field-for-a-model-field" title="Permalink to this headline">¶</a></h4>
<p>To customize the form field used by <a class="reference internal" href="../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><tt class="xref py py-class docutils literal"><span class="pre">ModelForm</span></tt></a>, you can
override <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.formfield" title="django.db.models.Field.formfield"><tt class="xref py py-meth docutils literal"><span class="pre">formfield()</span></tt></a>.</p>
<p>The form field class can be specified via the <tt class="docutils literal"><span class="pre">form_class</span></tt> and
<tt class="docutils literal"><span class="pre">choices_form_class</span></tt> arguments; the latter is used if the field has choices
specified, the former otherwise. If these arguments are not provided,
<a class="reference internal" href="../ref/forms/fields.html#django.forms.CharField" title="django.forms.CharField"><tt class="xref py py-class docutils literal"><span class="pre">CharField</span></tt></a> or <a class="reference internal" href="../ref/forms/fields.html#django.forms.TypedChoiceField" title="django.forms.TypedChoiceField"><tt class="xref py py-class docutils literal"><span class="pre">TypedChoiceField</span></tt></a>
will be used.</p>
<p>All of the <tt class="docutils literal"><span class="pre">kwargs</span></tt> dictionary is passed directly to the form field&#8217;s
<tt class="docutils literal"><span class="pre">__init__()</span></tt> method. Normally, all you need to do is set up a good default
for the <tt class="docutils literal"><span class="pre">form_class</span></tt> (and maybe <tt class="docutils literal"><span class="pre">choices_form_class</span></tt>) argument and then
delegate further handling to the parent class. This might require you to write
a custom form field (and even a form widget). See the <a class="reference internal" href="../topics/forms/index.html"><em>forms documentation</em></a> for information about this.</p>
<p>Continuing our ongoing example, we can write the <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.formfield" title="django.db.models.Field.formfield"><tt class="xref py py-meth docutils literal"><span class="pre">formfield()</span></tt></a> method
as:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">formfield</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="c"># This is a fairly standard way to set up some defaults</span>
        <span class="c"># while letting the caller override them.</span>
        <span class="n">defaults</span> <span class="o">=</span> <span class="p">{</span><span class="s">&#39;form_class&#39;</span><span class="p">:</span> <span class="n">MyFormField</span><span class="p">}</span>
        <span class="n">defaults</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">HandField</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">formfield</span><span class="p">(</span><span class="o">**</span><span class="n">defaults</span><span class="p">)</span>
</pre></div>
</div>
<p>This assumes we&#8217;ve imported a <tt class="docutils literal"><span class="pre">MyFormField</span></tt> field class (which has its own
default widget). This document doesn&#8217;t cover the details of writing custom form
fields.</p>
</div>
<div class="section" id="s-emulating-built-in-field-types">
<span id="s-id7"></span><span id="emulating-built-in-field-types"></span><span id="id7"></span><h4>Emulating built-in field types<a class="headerlink" href="#emulating-built-in-field-types" title="Permalink to this headline">¶</a></h4>
<p>If you have created a <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method, you don&#8217;t need to worry about
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_internal_type" title="django.db.models.Field.get_internal_type"><tt class="xref py py-meth docutils literal"><span class="pre">get_internal_type()</span></tt></a> &#8211; it won&#8217;t be used much. Sometimes, though, your
database storage is similar in type to some other field, so you can use that
other field&#8217;s logic to create the right column.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">get_internal_type</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&#39;CharField&#39;</span>
</pre></div>
</div>
<p>No matter which database backend we are using, this will mean that
<a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><tt class="xref std std-djadmin docutils literal"><span class="pre">migrate</span></tt></a> and other SQL commands create the right column type for
storing a string.</p>
<p>If <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.get_internal_type" title="django.db.models.Field.get_internal_type"><tt class="xref py py-meth docutils literal"><span class="pre">get_internal_type()</span></tt></a> returns a string that is not known to Django for
the database backend you are using &#8211; that is, it doesn&#8217;t appear in
<tt class="docutils literal"><span class="pre">django.db.backends.&lt;db_name&gt;.creation.data_types</span></tt> &#8211; the string will still be
used by the serializer, but the default <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> method will
return <tt class="docutils literal"><span class="pre">None</span></tt>. See the documentation of <a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.db_type" title="django.db.models.Field.db_type"><tt class="xref py py-meth docutils literal"><span class="pre">db_type()</span></tt></a> for reasons why
this might be useful. Putting a descriptive string in as the type of the field
for the serializer is a useful idea if you&#8217;re ever going to be using the
serializer output in some other place, outside of Django.</p>
</div>
<div class="section" id="s-converting-field-data-for-serialization">
<span id="s-converting-model-field-to-serialization"></span><span id="converting-field-data-for-serialization"></span><span id="converting-model-field-to-serialization"></span><h4>Converting field data for serialization<a class="headerlink" href="#converting-field-data-for-serialization" title="Permalink to this headline">¶</a></h4>
<p>To customize how the values are serialized by a serializer, you can override
<a class="reference internal" href="../ref/models/fields.html#django.db.models.Field.value_to_string" title="django.db.models.Field.value_to_string"><tt class="xref py py-meth docutils literal"><span class="pre">value_to_string()</span></tt></a>. Calling <tt class="docutils literal"><span class="pre">Field._get_val_from_obj(obj)</span></tt> is the
best way to get the value serialized. For example, since our <tt class="docutils literal"><span class="pre">HandField</span></tt> uses
strings for its data storage anyway, we can reuse some existing conversion code:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">HandField</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Field</span><span class="p">):</span>
    <span class="c"># ...</span>

    <span class="k">def</span> <span class="nf">value_to_string</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
        <span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_get_val_from_obj</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_prep_value</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-some-general-advice">
<span id="some-general-advice"></span><h3>Some general advice<a class="headerlink" href="#some-general-advice" title="Permalink to this headline">¶</a></h3>
<p>Writing a custom field can be a tricky process, particularly if you&#8217;re doing
complex conversions between your Python types and your database and
serialization formats. Here are a couple of tips to make things go more
smoothly:</p>
<ol class="arabic simple">
<li>Look at the existing Django fields (in
<tt class="file docutils literal"><span class="pre">django/db/models/fields/__init__.py</span></tt>) for inspiration. Try to find
a field that&#8217;s similar to what you want and extend it a little bit,
instead of creating an entirely new field from scratch.</li>
<li>Put a <tt class="docutils literal"><span class="pre">__str__()</span></tt> (<tt class="docutils literal"><span class="pre">__unicode__()</span></tt> on Python 2) method on the class you&#8217;re
wrapping up as a field. There are a lot of places where the default
behavior of the field code is to call
<a class="reference internal" href="../ref/utils.html#django.utils.encoding.force_text" title="django.utils.encoding.force_text"><tt class="xref py py-func docutils literal"><span class="pre">force_text()</span></tt></a> on the value. (In our
examples in this document, <tt class="docutils literal"><span class="pre">value</span></tt> would be a <tt class="docutils literal"><span class="pre">Hand</span></tt> instance, not a
<tt class="docutils literal"><span class="pre">HandField</span></tt>). So if your <tt class="docutils literal"><span class="pre">__str__()</span></tt> method (<tt class="docutils literal"><span class="pre">__unicode__()</span></tt> on
Python 2) automatically converts to the string form of your Python object,
you can save yourself a lot of work.</li>
</ol>
</div>
</div>
<div class="section" id="s-writing-a-filefield-subclass">
<span id="writing-a-filefield-subclass"></span><h2>Writing a <tt class="docutils literal"><span class="pre">FileField</span></tt> subclass<a class="headerlink" href="#writing-a-filefield-subclass" title="Permalink to this headline">¶</a></h2>
<p>In addition to the above methods, fields that deal with files have a few other
special requirements which must be taken into account. The majority of the
mechanics provided by <tt class="docutils literal"><span class="pre">FileField</span></tt>, such as controlling database storage and
retrieval, can remain unchanged, leaving subclasses to deal with the challenge
of supporting a particular type of file.</p>
<p>Django provides a <tt class="docutils literal"><span class="pre">File</span></tt> class, which is used as a proxy to the file&#8217;s
contents and operations. This can be subclassed to customize how the file is
accessed, and what methods are available. It lives at
<tt class="docutils literal"><span class="pre">django.db.models.fields.files</span></tt>, and its default behavior is explained in the
<a class="reference internal" href="../ref/files/file.html"><em>file documentation</em></a>.</p>
<p>Once a subclass of <tt class="docutils literal"><span class="pre">File</span></tt> is created, the new <tt class="docutils literal"><span class="pre">FileField</span></tt> subclass must be
told to use it. To do so, simply assign the new <tt class="docutils literal"><span class="pre">File</span></tt> subclass to the special
<tt class="docutils literal"><span class="pre">attr_class</span></tt> attribute of the <tt class="docutils literal"><span class="pre">FileField</span></tt> subclass.</p>
<div class="section" id="s-a-few-suggestions">
<span id="a-few-suggestions"></span><h3>A few suggestions<a class="headerlink" href="#a-few-suggestions" title="Permalink to this headline">¶</a></h3>
<p>In addition to the above details, there are a few guidelines which can greatly
improve the efficiency and readability of the field&#8217;s code.</p>
<ol class="arabic simple">
<li>The source for Django&#8217;s own <tt class="docutils literal"><span class="pre">ImageField</span></tt> (in
<tt class="docutils literal"><span class="pre">django/db/models/fields/files.py</span></tt>) is a great example of how to
subclass <tt class="docutils literal"><span class="pre">FileField</span></tt> to support a particular type of file, as it
incorporates all of the techniques described above.</li>
<li>Cache file attributes wherever possible. Since files may be stored in
remote storage systems, retrieving them may cost extra time, or even
money, that isn&#8217;t always necessary. Once a file is retrieved to obtain
some data about its content, cache as much of that data as possible to
reduce the number of times the file must be retrieved on subsequent
calls for that information.</li>
</ol>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Writing custom model fields</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a><ul>
<li><a class="reference internal" href="#our-example-object">Our example object</a></li>
</ul>
</li>
<li><a class="reference internal" href="#background-theory">Background theory</a><ul>
<li><a class="reference internal" href="#database-storage">Database storage</a></li>
<li><a class="reference internal" href="#what-does-a-field-class-do">What does a field class do?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#writing-a-field-subclass">Writing a field subclass</a><ul>
<li><a class="reference internal" href="#field-deconstruction">Field deconstruction</a></li>
<li><a class="reference internal" href="#the-subfieldbase-metaclass">The <tt class="docutils literal"><span class="pre">SubfieldBase</span></tt> metaclass</a><ul>
<li><a class="reference internal" href="#modelforms-and-custom-fields"><tt class="docutils literal"><span class="pre">ModelForm</span></tt>s and custom fields</a></li>
</ul>
</li>
<li><a class="reference internal" href="#documenting-your-custom-field">Documenting your custom field</a></li>
<li><a class="reference internal" href="#useful-methods">Useful methods</a><ul>
<li><a class="reference internal" href="#custom-database-types">Custom database types</a></li>
<li><a class="reference internal" href="#converting-database-values-to-python-objects">Converting database values to Python objects</a></li>
<li><a class="reference internal" href="#converting-python-objects-to-query-values">Converting Python objects to query values</a></li>
<li><a class="reference internal" href="#converting-query-values-to-database-values">Converting query values to database values</a></li>
<li><a class="reference internal" href="#preprocessing-values-before-saving">Preprocessing values before saving</a></li>
<li><a class="reference internal" href="#preparing-values-for-use-in-database-lookups">Preparing values for use in database lookups</a></li>
<li><a class="reference internal" href="#specifying-the-form-field-for-a-model-field">Specifying the form field for a model field</a></li>
<li><a class="reference internal" href="#emulating-built-in-field-types">Emulating built-in field types</a></li>
<li><a class="reference internal" href="#converting-field-data-for-serialization">Converting field data for serialization</a></li>
</ul>
</li>
<li><a class="reference internal" href="#some-general-advice">Some general advice</a></li>
</ul>
</li>
<li><a class="reference internal" href="#writing-a-filefield-subclass">Writing a <tt class="docutils literal"><span class="pre">FileField</span></tt> subclass</a><ul>
<li><a class="reference internal" href="#a-few-suggestions">A few suggestions</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="custom-management-commands.html">Writing custom django-admin commands</a></li>
    
    
      <li>Next: <a href="custom-lookups.html">Custom Lookups</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../index.html">Django 1.7.8.dev20150401230226 documentation</a>
        
          <ul><li><a href="index.html">&#8220;How-to&#8221; guides</a>
        
        <ul><li>Writing custom model fields</li></ul>
        </li></ul>
      </li>
  </ul>

  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../_sources/howto/custom-model-fields.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Apr 02, 2015</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="custom-management-commands.html" title="Writing custom django-admin commands">previous</a>
     |
    <a href="index.html" title="&amp;#8220;How-to&amp;#8221; guides" accesskey="U">up</a>
   |
    <a href="custom-lookups.html" title="Custom Lookups">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>